package com.gid.rcflightlogger;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;

import com.orm.androrm.Filter;

public class BatteryLogBrowseActivity extends BaseActivity {

	
	//db objects
	private List<Cycle> mCycles;	//all cycles
	private List<Battery> mBatteries;
	private Battery mEmptyBattery;
	
	//data used for log filtering
	private ArrayAdapter<Battery> mBatterySpinnerAdapter;
	private ArrayAdapter<String> mTimeFilterSpinnerAdapter;
	private final String[] mTimeFilterLabels =	{"",	"Today",				"Last week", 			"Last month",			"Last 3 months",			"Last 6 months",			"Last year", 				"Last 2 years", 			"Last 3 years"};
	private final long[] mTimeFilterOffsets =	{0,		(long)24*60*60*1000,	(long)7*24*60*60*1000,	(long)30*24*60*60*1000,	(long)3*30*24*60*60*1000,	(long)6*30*24*60*60*1000,	(long)12*30*24*60*60*1000,	(long)24*30*24*60*60*1000, 	(long)36*30*24*60*60*1000}; //in milliseconds
	
	//layout objects
	private TextView mHeader;
	private ListView mCycleList;
	private CycleListAdapter mCycleListAdapter;
	private Spinner mBatterySpinner;
	private Spinner mTimeFilterSpinner;
	
	private int mSelectedId = 0;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_batterylogbrowse);
        mCurrentMenuID = R.id.menu_main_logs_cycles;
        LOG_TAG = "BatteryLogBrowse";
        
        mCycles = new ArrayList<Cycle>();
        mBatteries = new ArrayList<Battery>();
        mEmptyBattery = new Battery();
        mBatterySpinnerAdapter = new ArrayAdapter<Battery>(this, android.R.layout.simple_spinner_item, mBatteries);
        mTimeFilterSpinnerAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, mTimeFilterLabels);
        
        mHeader = (TextView) findViewById(R.id.batterylogbrowse_header);
        mCycleList = (ListView) findViewById(R.id.batterylogbrowse_loglist);
        mCycleListAdapter = new CycleListAdapter(this);
        mCycleList.setAdapter(mCycleListAdapter);
        mCycleList.setOnItemLongClickListener(mLogItemLongClickListener);
        
        mBatterySpinner = (Spinner) findViewById(R.id.batterylogbrowse_spinner_battery);
        mBatterySpinner.setAdapter(mBatterySpinnerAdapter);
        mBatterySpinner.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				filterAndDisplayData();
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				filterAndDisplayData();
			}
		});
        mTimeFilterSpinner = (Spinner) findViewById(R.id.batterylogbrowse_spinner_time);
        mTimeFilterSpinner.setAdapter(mTimeFilterSpinnerAdapter);
        mTimeFilterSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				filterAndDisplayData();
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				filterAndDisplayData();
			}
		});
	}
	
    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onResume() {
        super.onResume();
        loadData();
        filterAndDisplayData();
    }
	
	private void loadData() {
		//reload data from database
		mCycles.clear();
		Filter cfilter = new Filter();
		cfilter.is("mFake", 0);
		mCycles.addAll(Cycle.objects(getApplicationContext()).filter(cfilter).orderBy("-mDate").toList());
		
		mBatteries.clear();
		mBatteries.add(mEmptyBattery);
		mBatteries.addAll(Battery.objects(getApplicationContext()).all().toList());
		mBatterySpinnerAdapter.notifyDataSetChanged();
	}
	
	private void filterAndDisplayData() {
		int matchId = 0;
		if (mBatterySpinner.getSelectedItemPosition() > 0)
		{
			matchId = ((Battery)(mBatterySpinner.getSelectedItem())).getId();
		}
		
		Date matchFromDate = null;
		if (mTimeFilterSpinner.getSelectedItemPosition() > 0)
		{
			matchFromDate = new Date();
			long ms = matchFromDate.getTime();
			ms = ms - mTimeFilterOffsets[mTimeFilterSpinner.getSelectedItemPosition()];
			matchFromDate.setTime(ms);
			//myUtils.makeToast(this, "Pos = " + mTimeFilterSpinner.getSelectedItemPosition() + " Offset = " + mTimeFilterOffsets[mTimeFilterSpinner.getSelectedItemPosition()] + " Time = " + myUtils.Date2Str(matchFromDate));
		}
		
		//repopulate log list
		mCycleListAdapter.clear();
		int totalCycles = 0;
		int totalDuration = 0;
		
		for (Cycle c : mCycles) 
		{
			//skip if filtering criteria not matched
			if ( ((matchId != 0) && (c.getBattery(this).getId() != matchId)) || ((matchFromDate != null) && (c.getDate().before(matchFromDate))))
				continue;
			
			totalCycles += c.getCount();
			totalDuration += c.getDuration();
			
			mCycleListAdapter.add(c);
		}
		
		//update summary text
		mHeader.setText("TOTAL: " + totalCycles + " cycle" + ((totalCycles > 1) ? "s" : "") + " in " + myUtils.Duration2Str(totalDuration, true));
		mCycleListAdapter.notifyDataSetChanged();
	}
	
	private AdapterView.OnItemLongClickListener mLogItemLongClickListener = new AdapterView.OnItemLongClickListener()
    {
		@Override
		public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
				int arg2, long arg3) {
			
			mSelectedId = ((Cycle)arg0.getItemAtPosition(arg2)).getId();
			AlertDialog.Builder builder = new AlertDialog.Builder(BatteryLogBrowseActivity.this);
			builder.setMessage("Delete this battery cycle log entry?").setCancelable(false);
			builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int id) {
					Cycle c = Cycle.objects(BatteryLogBrowseActivity.this).get(mSelectedId);
					if (c != null)
					{
						c.delete(BatteryLogBrowseActivity.this);
						loadData();
						filterAndDisplayData();
					}
				}
			});
			builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int id) {
					dialog.cancel();
				}
			});
			AlertDialog alert = builder.create();
			alert.show();
			return true;
    	}
    };
}
